package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.aop.Aopannotation;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
/*
    菜品管理
 */
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    @Aopannotation(type = "新增菜品")
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
//        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
//        redisTemplate.delete(keys); //删除这些key
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增成功");
    }

    /*
        菜品分页查询
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //1). 构造分页条件对象
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //2). 构建查询及排序条件
        //SELECT * FROM dish WHERE NAME LIKE '%xx%' ORDER BY update_time DESC LIMIT 0 ,10
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //模糊查询条件 WHERE NAME LIKE '%xx%'
        lqw.like(name != null, Dish::getName, name);
        //ORDER BY update_time DESC
        lqw.orderByDesc(Dish::getUpdateTime);
        //3). 执行分页条件查询
        dishService.page(dishPage, lqw);
        //4). 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        //对象拷贝  将pageInfo对象上所有的属性赋值到dishDtoPage对象上,但是不包括records属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();

        //设置一个集合,存入各个dishDto对象
        ArrayList<DishDto> records2 = new ArrayList<>();
        for (Dish record : records) {
            //创建dishdto,拷贝属性
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            //根据dishDto的菜品分类ID查询菜品分类对象,设置分类名称
            Category category = categoryService.getById(dishDto.getCategoryId());
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            records2.add(dishDto);
        }
        //将集合设置到dishDtoPage对象上
        dishDtoPage.setRecords(records2);
        //5). 封装数据并返回

        return R.success(dishDtoPage);
    }

    //根据id查询菜品信息和对应的口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    @Aopannotation(type = "修改菜品")
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }
    //根据条件查询对应的菜品数据
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        log.info(dish.toString());
        List<DishDto> list02 = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        list02 = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(list02 != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(list02);
        }

        //---------------------------------------------------
        //不存在查询数据库，并将数据库查询结果，缓存在redis，并设置过期时间
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        //排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lqw);

        list02=new ArrayList<>();
        //创建集合,存放的是DishDto
        for (Dish ds : list) {
            //创建DishDto
            DishDto dishDto=new DishDto();
            //将ds所有属性复制到DishDto
            BeanUtils.copyProperties(ds,dishDto);
            //根据ds查询ds对应的口味信息
            Long dishId=ds.getId();
            //根据dishId查询口味  SELECT * FROM dish_flavor WHERE dish_id='1397849739276890114'
            LambdaQueryWrapper<DishFlavor> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list1 = dishFlavorService.list(lqw2);
            //键改口味设置到DishDto
            dishDto.setFlavors(list1);
            list02.add(dishDto);
        }
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,list02,60, TimeUnit.MINUTES);
        return R.success(list02);

    }
}
